/*
 ============================================================================
 Name        : channel_para.c
 Author      : water
 Version     :
 Copyright   : Your copyright notice
 Description : Hello World in C, Ansi-style
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include "sqlite3.h"
#include "cgi.h"
#include "cookie.h"


void putJSON(char **azResult, int nrow, int ncolumn);
void putHTML(char **azResult, int nrow, int ncolumn);

sqlite3  *db  = NULL;

void getIndex(char *s){
	int len = strlen(s);
	int i = 0;
	while(i<len){
		if('1' == s[i]){
			printf("%d,", len - i);
		}
		i++;
	}
}

void put_error(char *err_msg){
    printf("Content-type:text/html;charset=UTF-8\n\n");
	printf("%s.\n", err_msg);
}

int get_channels(PARAM phaseId, char *str){
    int      nrow=0,ncolumn=0;
    char     **azResult = NULL;
    char     *zErrMsg = 0;
    int      rc;
    char     sql[500];
    /* get phase channel */
    if( strcmp(phaseId.value, "") != 0 && strcmp(phaseId.value, "null") != 0 ){
         if(strcmp(phaseId.value, "0") == 0)
            sprintf(sql, "select channel_index from [tb_channel_parm] where channel_ctrl_signal_source = -1 ");
        else
            sprintf(sql, "select channel_index from [tb_channel_parm] where channel_ctrl_signal_source = %s ", phaseId.value);
    }
    rc = sqlite3_get_table(db, sql, &azResult, &nrow, &ncolumn, &zErrMsg);
    if (rc != SQLITE_OK) {
        fprintf(stderr,"SQL error:%s\n", zErrMsg);
        put_error(zErrMsg);
        sqlite3_close(db);
        return 0;
    } 
    if (*azResult != NULL) {
        char ch[500];
		int i=0, j=0, n=0;
        for(i=1; i<=nrow; i++) {
		    char *phaseIndex = {0};
            for(j=0; j<ncolumn; j++) {
			    if(j==0){
				    phaseIndex = azResult[ (i*ncolumn) + j ];
			    }
                printf("%s", azResult[ (i*ncolumn) + j ]); // column value               
                n++;
            }
            if(i == nrow)
			    printf(" ");
		    else
			    printf(", ");
        }
    }
    return 0;
}

int main(void) {
    int      nrow=0,ncolumn=0;
    char     **azResult = NULL;
    char     *zErrMsg = 0;
    char     sql[500];
    char     *input;
    char     *req_method;
    int      rc;

    if(isvalid_cookie()!=0){
        return 0;
    }


    rc = sqlite3_open(PATH_DATABASE,&db);
    if (rc) {
        fprintf(stderr,"Can't open database:%s\n",sqlite3_errmsg(db));
        sqlite3_close(db);
        return 0;

    } else {

        req_method = getenv("REQUEST_METHOD");

        FILE* fp = (FILE*) stdin;
        input = getcgidata(fp, req_method);

        PARAM stageTimingId = getParam(input, "stageTimingId");
        PARAM stageId = getParam(input, "stageId");
        //
        PARAM dataType = getParam(input, "dataType");

        if( strcmp(stageId.value, "") != 0 && strcmp(stageId.value, "null") != 0 &&
            strcmp(stageTimingId.value, "") != 0 && strcmp(stageTimingId.value, "null") != 0){
            sprintf(sql, "select * from [TB_STAGE_TIMING] \
             where STAGE_TIMING_INDEX = '%s' and STAGE_INDEX = '%s' order by STAGE_TIMING_INDEX, STAGE_INDEX ", 
                stageTimingId.value, stageId.value);
        } else if(strcmp(stageTimingId.value, "") != 0 && strcmp(stageTimingId.value, "null") != 0){
            sprintf(sql, "select * from [TB_STAGE_TIMING] where STAGE_TIMING_INDEX = '%s' order by STAGE_TIMING_INDEX ", stageTimingId.value);
        } else if( strcmp(stageId.value, "") != 0 && strcmp(stageId.value, "null") != 0 ){
            sprintf(sql, "select * from [TB_STAGE_TIMING] where STAGE_INDEX = '%s' order by STAGE_INDEX ", stageId.value);
        } else {
            sprintf(sql, "select * from [TB_STAGE_TIMING] order by STAGE_TIMING_INDEX, STAGE_INDEX ");
        }

        //printf("%s", sql);

        rc = sqlite3_get_table(db,sql,&azResult,&nrow,&ncolumn,&zErrMsg);
        if (rc != SQLITE_OK) {
            fprintf(stderr,"SQL error:%s\n", zErrMsg);
            sqlite3_close(db);
            return 0;

        } if (*azResult != NULL) {
            // choose data format
            if( strcmp(dataType.value, "json") == 0 ){
                putJSON(azResult, nrow, ncolumn);
            } else {
                putHTML(azResult, nrow, ncolumn);
            }

        }
    }

    sqlite3_close(db);
    return 0;

}


void putJSON(char **azResult, int nrow, int ncolumn){
    int i=0, j=0, n=0;
    printf("Content-type:text/json;charset=UTF-8\n\n");
    printf("{ \"rows\": \"%d\", \"data\": [", nrow);
    for(i=1; i<=nrow; i++) {
 
        printf("{");
        char *phaseIndex = {0};
        for(j=0; j<ncolumn; j++) {
            if(j==0){
                phaseIndex = azResult[ (i*ncolumn) + j ];
            }
            printf("\"%s\": \"", azResult[j]);
            printf("%s", azResult[ (i*ncolumn) + j ]);
            if(j == ncolumn-1)
                printf("\"");
            else
                printf("\",");
            n++;
            if( strcmp(azResult[j], "pass_phase") == 0 ){ // insert lane
                //printf("\"%s\":\"", azResult[j]);//phaseLanes
                /*
                printf("\"phaseLanes\":\"");//
	            PARAM p;
                sprintf(p.value, "%s", azResult[ (i*ncolumn) + j ]);
                get_channels(p, NULL);
                printf("\",");
                */
                
                printf("\"phases\":\"");//
                char str[32] = {0};                
                int phase = atoi(azResult[ (i*ncolumn) + j ]);
                _itoa(phase, str, 2);
                getIndex(str); 
                 printf("\",");
            }
        }
        if(i == nrow)
            printf("}\n\n");
        else
            printf("},\n\n");
    }
    printf("]}");
}


void putHTML(char **azResult, int nrow, int ncolumn){
    int i=0, j=0, n=0;
    printf("Content-type:text/html;charset=UTF-8\n\n");
    printf("<table res=\"%d\" id=\"logTbl\" class=\"dataGrid\">", nrow);
    printf("<tr>\
        <th>阶段配时方案号</th>\
        <th>阶段号</th>\
        <th>放行相位</th>\
        <th>阶段绿灯时间</th>\
        <th>阶段黄灯时间</th>\
        <th>阶段红灯时间</th>\
        <th>选项参数</th>\
        <th>修改时间</th>\
        <th>选项</th></tr>\n\n");

    for(i=1; i<=nrow; i++) {
        printf("<tr>");
        char *stIndex = {0},*sIndex = {0};
        for(j=0; j<ncolumn; j++) {
            if(j==0){
                stIndex = azResult[ (i*ncolumn) + j ];
            }
            if(j==1){
                sIndex = azResult[ (i*ncolumn) + j ];
            }
            printf("<td>");
            printf("%s", azResult[ (i*ncolumn) + j ]);
            printf("</td>");
            n++;
        }

        printf("<td>\
                    <input type=\"button\" class=\"edit-btn\" title=\"编辑\" onclick=\"editStageTiming(%s,%s)\"   />\
                    <input type=\"button\" class=\"dele-btn\" title=\"删除\" onclick=\"deleteStageTiming(%s,%s)\" />\
              </td>", stIndex, sIndex, stIndex, sIndex);

        printf("<tr>\n\n");
    }
    printf("</table>");
}


